#include <cairo.h>  
#include <gtk/gtk.h>  
#include <math.h>  
   
cairo_surface_t *image;


static gboolean  
on_expose_event(GtkWidget *widget,  
    GdkEventExpose *event,  
    gpointer data)  
{  
  cairo_t *cr;  
  cr = gdk_cairo_create(widget->window);  
   
  static gboolean xdirection = TRUE;  
  static gint counter = 0;  
   
  int width, height;  
  gtk_window_get_size(GTK_WINDOW(widget), &width, &height);  
   
  static gdouble rotate = 0;  
   
  static gint bigx = 20;  
  static gint bigy = 200;  
  static gint delta = 1;  
   
  counter += 1;   
   
   
  if(bigx > width) {  
      xdirection = FALSE;  
      delta = -delta;  
      bigx = width;  
  }  
   
  if(bigx < 1) {  
      bigx = 1;  
      delta = -delta;  
  }  
   
  if(bigy > height) {  
      xdirection = TRUE;  
      delta = -delta;  
      bigy = height;  
  }  
   
  if(bigy < 1) {  
      delta = -delta;  
      bigy = 1;  
  }  
   
  if(xdirection) {  
      bigx += delta;  
  }else {  
      bigy += delta;  
  }  
   
  cairo_set_source_surface(cr, image, 1, 1); 
  
  /* */
  cairo_translate(cr, width / 2, height /2);  
   
  /*cairo_rectangle(cr, 左上顶点X, 左上顶点Y, 宽, 高);  */
  cairo_rectangle(cr, -bigx/2, -bigy/2, bigx, bigy);  
  cairo_set_line_width(cr, 2);   
  cairo_stroke(cr);   
     
  cairo_rotate(cr, rotate);  
  rotate += 0.01;  
   
  cairo_rectangle(cr, -50, -25, 100, 50);  
  cairo_stroke(cr);  
   
  GdkRectangle bigrect;  
  GdkRectangle rect;  
  GdkRectangle intersect;  
   
  bigrect.x = -bigx/2;  
  bigrect.y = -bigy/2;  
  bigrect.width = bigx;  
  bigrect.height = bigy;  
   
  rect.x = -50;  
  rect.y = -25;  
  rect.width = 100;  
  rect.height = 50;  

  gdk_rectangle_intersect(&bigrect, &rect, &intersect);  
  printf("%d %d %d %d\n", intersect.x, intersect.y, intersect.width, intersect.height);
  cairo_rectangle(cr, intersect.x, intersect.y, intersect.width, intersect.height);  
  cairo_fill(cr);  
   
  cairo_destroy(cr);  
   
  return FALSE;  
}  
   
static gboolean  
time_handler (GtkWidget *widget)  
{  
  if(widget->window == NULL) return FALSE;  
  gtk_widget_queue_draw(widget);  
  return TRUE;  
}  
   
int  
main (int argc, char *argv[])  
{  
   
  GtkWidget *window;  
   
  gtk_init(&argc, &argv);  
  /* 从文件中加载一张图片，作为cairo的源 */
  image = cairo_image_surface_create_from_png("../assert/turnacastle.png");
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);  
   
  g_signal_connect(G_OBJECT(window),"expose-event",  
      G_CALLBACK(on_expose_event), NULL);  
  g_signal_connect(G_OBJECT(window),"destroy",  
      G_CALLBACK(gtk_main_quit), NULL);  
   
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);  
  gtk_window_set_default_size(GTK_WINDOW(window), 250, 200);  
   
  gtk_widget_set_app_paintable(window, TRUE);  
  gtk_widget_show_all(window);  
  g_timeout_add(10, (GSourceFunc) time_handler, (gpointer) window);  
   
  gtk_main();  
   
  return 0;  
}  
